var letters = [];
var words = [];
var results = [];
var started = undefined;

var MIN_WORD_SIZE = 3;
var TIME_LIMIT = 5;


var CUBES = [
    ["AAEEGN", "ELRTTY", "AOOTTW", "ABBJOO"],
    ["EHRTVW", "CIMOTU", "DISTTY", "EIOSST"],
    ["DELRVY", "ACHOPS", "HIMNQU", "EEINSU"],
    ["EEGHNW", "AFFKPS", "HLNNRZ", "DEILRX"]
];

function populateLetters() {
    var letters = [];
    for (var y = 0; y < CUBES.length; y++) {
        var row = [];
        for (var x = 0; x < CUBES[y].length; x++) {
            var cube = CUBES[y][x];
            var letter = cube.charAt(Math.floor(Math.random() * cube.length));
            row.push(letter);
        }
        letters.push(row);
    }
    return letters;
}

function populateBoard() {
    var board = document.getElementById('board');

    var table = '<table>';
    for (var y=0; y<letters.length; y++){
        table += "<tr>";
        for (var x=0; x<letters[y].length; x++){
            table += "<td>" + letters[y][x] + "</td>";
        }
        table += "</tr>";
    }
    table += '</table>';

    board.innerHTML = table;

    document.getElementById('wordInput').focus();
}

function displayBoard() {
    document.getElementById('results').style.display = 'none';
    document.getElementById('mainDiv').style.display = 'block';
}

function clearResults() {
    document.getElementById('wordList').innerHTML = '';
    document.getElementById('wordResult').innerHTML = '';
    document.getElementById('results').innerHTML = '';
    document.getElementById('wordInput').disabled = false;
    results = [];
    started = null;
    words = [];
    letters = [];
}

function startTimer() {
    document.getElementById('timer').innerHTML = TIME_LIMIT;
    started = new Date().getTime();

    var timerId;
    timerId = setInterval(function() {
        var time = new Date().getTime() - started;
        var secondsLeft = TIME_LIMIT - Math.floor(time / 1000);
        document.getElementById('timer').innerHTML = secondsLeft;
        if (secondsLeft == 0) {
            document.getElementById('wordInput').disabled = 'disabled';
            clearInterval(timerId);

            // fire event
            var evt = document.createEvent('Event');
            evt.initEvent('timerExpired', true, false);
            document.dispatchEvent(evt);
        }
        else if (secondsLeft < 15) {
            document.getElementById('timer').className = 'timer-warn';
        }
    }, 500)
}

function checkWordInDictionary(word) {
    //console.log('checking: ' + word);
    var regex = new RegExp('\\*' + word + '\\*');
    //console.log('result: ' + regex.test(dictionary));
    if (regex.test(dictionary)) {
        return true;
    }
    return false;
}

function checkLetterInBoard(letter) {
    var positions  = [];
    for (var y=0; y<4; y++){
        for (var x=0; x<4; x++){
            if (letters[y][x] == letter) {
                positions.push({y: y, x: x});
            }
        }
    }
    return positions;
}

function checkNextLetter(letter, position) {
    console.log('checking: ' + letter + ' at: ' + position.y + ',' + position.x);

    var minY = (position.y - 1 < 0)? 0 : (position.y - 1);
    var maxY = (position.y + 1 > 3)? 3 : (position.y + 1);

    var minX = (position.x - 1 < 0)? 0 : (position.x - 1);
    var maxX = (position.x + 1 > 3)? 3 : (position.x + 1);

    var positions = [];
    for (var y = minY; y <= maxY; y++) {
        for (var x = minX; x <= maxX; x++) {
            if (!(y == position.y && x == position.x)) {
                if (letters[y][x] == letter) {
                    positions.push({y: y, x: x});
                }
            }
        }
    }
    return positions;
}

function checkDuplicate(word) {
    for (var i = 0; i < words.length; i++) {
        if (words[i] == word) {
            return false;
        }
    }
    return true;
}

function checkWordInBoard(word) {
    if (word.length < 1) {
        return false;
    }
    var firstCh = word.charAt(0).toUpperCase();
    var positions = checkLetterInBoard(firstCh);
    for (var i = 1; i < word.length; i++) {
        var ch = word.charAt(i).toUpperCase();
        var newPositions = [];
        for (var j = 0; j < positions.length; j++) {
            var result = checkNextLetter(ch, positions[j]);
            for (var k = 0; k < result.length; k++) {
                newPositions.push(result[k]);
            }
        }

        if (newPositions.length == 0) {
            return false;
        }
        positions = newPositions;
    }
    return true;
}

function testWord() {
    var word = document.getElementById('wordInput').value;

    if (word.length < MIN_WORD_SIZE) {
        writeBadResult(word, ' is not long enough')
        return false;
    }

    if (!checkDuplicate(word)) {
        writeBadResult(word, ' is a duplicate');
        return false;
    }

    if (!checkWordInBoard(word)) {
        writeBadResult(word, ' is not valid')
        return false;
    }

    if (!checkWordInDictionary(word)) {
        writeBadResult(word, ' is not in the dictionary')
        return false;
    }

    writeGoodResult(word);
    return true;
}

function writeBadResult(word, result) {
    var text = word + ' ' + result;
    console.log(text);
    var wordResult = document.getElementById('wordResult');
    wordResult.innerHTML = text;
    wordResult.className = 'bad-result';
}

function writeGoodResult(word) {
    var text = word + ' is valid';
    console.log(text);
    var wordResult = document.getElementById('wordResult');
    wordResult.innerHTML = text;
    wordResult.className = 'good-result';
}

function submitWord(e) {
    if (e && e.keyCode == 13) {
        var word = document.getElementById('wordInput').value;
        if (testWord()) {
            words.push(word);
            document.getElementById('wordList').innerHTML += '<li>' + word + '</li>';
        }
        document.getElementById('wordInput').value = '';
    }
}

function updateTime() {

}